package com.sailfish.springbootdemo.service.db2.impl;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db2.PcbOpenCapacityAuthenticationDao;
import com.sailfish.springbootdemo.dao.db2.PcbParentFactoryInfoDao;
import com.sailfish.springbootdemo.dao.db2.PcbSonFactoryInfoDao;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.PcbOpenCapacityAuthentication;
import com.sailfish.springbootdemo.pojo.db2.PcbParentFactoryInfo;
import com.sailfish.springbootdemo.pojo.db2.PcbSonFactoryInfo;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.PcbParentFactoryInfoService;
import com.sailfish.springbootdemo.service.db2.S3UploadFileService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ExcelStyleUtil;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PcbParentFactoryInfoServiceImpl implements PcbParentFactoryInfoService {

    @Autowired
    PcbParentFactoryInfoDao pcbParentFactoryInfoDao;
    @Autowired
    PcbSonFactoryInfoDao pcbSonFactoryInfoDao;
    @Autowired
    PcbOpenCapacityAuthenticationDao pcbOpenCapacityAuthenticationDao;
    @Autowired
    OperateService operateService;
    @Autowired
    UserDao userDao;
    @Autowired
    S3UploadFileService s3UploadFileService;

    @Override
    public List<PcbParentFactoryInfo> getAll(String companyName, String companyNameFull, String companyCode, String companyNameEn, String companyWebsite, String factoryName, String factoryNameEn, String factoryIntroduction,
                                             String factoryIntroductionEn, String factoryContacts, String factoryCategory, String factoryCategoryEn, Integer status, String remarkPic) {
        PcbParentFactoryInfo search2 = new PcbParentFactoryInfo();
        search2.setStatus(status);
        if (!StringUtils.isBlank(companyName)) {
            search2.setCompanyName(companyName);
        }
        if (!StringUtils.isBlank(companyNameFull)) {
            search2.setCompanyNameFull(companyNameFull);
        }
        if (!StringUtils.isBlank(companyNameEn)) {
            search2.setCompanyNameEn(companyNameEn);
        }
        if (!StringUtils.isBlank(companyCode)) {
            search2.setCompanyCode(companyCode);
        }
        if (!StringUtils.isBlank(companyWebsite)) {
            search2.setCompanyWebsite(companyWebsite);
        }
        Integer belongPcb = null;
        String userId = UserHeaderHolder.getUserId();
        if (!StringUtils.isBlank(userId)) {
            User userInfoById = userDao.getUserInfoById(Integer.parseInt(userId));
            if (userInfoById.getIsInner() != null && userInfoById.getIsInner() == 2) {
                belongPcb = userInfoById.getBelongPcb();
                if (belongPcb != null) {
                    PcbSonFactoryInfo pcbSonFactoryInfo = pcbSonFactoryInfoDao.getById(belongPcb);
                    List<PcbSonFactoryInfo> pcbSonFactoryInfoList = new ArrayList<>();
                    pcbSonFactoryInfoList.add(pcbSonFactoryInfo);

                    Integer parentId = pcbSonFactoryInfo.getParentId();
                    PcbParentFactoryInfo pcbParentFactoryInfo = pcbParentFactoryInfoDao.getById(parentId);
                    pcbParentFactoryInfo.setSonFactoryInfos(pcbSonFactoryInfoList);
                    List<PcbParentFactoryInfo> list = new ArrayList<>();
                    list.add(pcbParentFactoryInfo);
                    for (PcbParentFactoryInfo pcbParentFactoryInfo2 : list) {
                        if(pcbParentFactoryInfo2.getRemarkPic() != null && !"".equals(pcbParentFactoryInfo2.getRemarkPic())){
                            String base64Image = s3UploadFileService.getImageBase64FromUrl(pcbParentFactoryInfo2.getRemarkPic());
                            pcbParentFactoryInfo2.setImageBase64(CommonUtils.base64Prefix() + base64Image);
                        }
                    }
                    return list;
                }
            }
        }


        List<PcbParentFactoryInfo> allByLimit = pcbParentFactoryInfoDao.getAllByLimit(search2);
        for (PcbParentFactoryInfo item : allByLimit) {
            PcbSonFactoryInfo search = new PcbSonFactoryInfo();
            search.setParentId(item.getPcbParentFactoryId());
            search.setStatus(status);
            List<PcbSonFactoryInfo> pcbSons = pcbSonFactoryInfoDao.getAllByLimit(search);
            item.setSonFactoryInfos(pcbSons);
            if(item.getRemarkPic() != null && !"".equals(item.getRemarkPic())){
                String base64Image = s3UploadFileService.getImageBase64FromUrl(item.getRemarkPic());
                item.setImageBase64(CommonUtils.base64Prefix() + base64Image);
            }
        }
        return allByLimit;
    }

    @Override
    public List<PcbParentFactoryInfo> getAll() {
        PcbParentFactoryInfo search = new PcbParentFactoryInfo();
        search.setStatus(1);
        List<PcbParentFactoryInfo> pcbParentFactoryInfoList = pcbParentFactoryInfoDao.getAllByLimit(search);
        return pcbParentFactoryInfoList;
    }

    @Override
    public List<PcbParentFactoryInfo> getBySonList(List<Integer> sonIds, Integer flag) {
        List<PcbParentFactoryInfo> result = null;
        if (sonIds == null) {
            result = getAll(null, null, null, null, null, null, null, null, null, null, null, null, 1, null);
        } else {
            List<PcbSonFactoryInfo> sonFactoryInfoMap = new ArrayList<>();
            List<PcbParentFactoryInfo> pcbParentFactoryInfoMap = new ArrayList<>();
            List<Integer> parentIds = new ArrayList<>();
            for (int i = 0; i < sonIds.size(); i++) {
                Integer sonId = sonIds.get(i);
                PcbSonFactoryInfo pcbSonFactoryInfo = pcbSonFactoryInfoDao.getById(sonId);
                if (pcbSonFactoryInfo != null) {
                    sonFactoryInfoMap.add(pcbSonFactoryInfo);
                }

                PcbParentFactoryInfo pcbParentFactoryInfo = pcbParentFactoryInfoDao.getById(pcbSonFactoryInfo.getParentId());
                Integer parentId = pcbParentFactoryInfo.getPcbParentFactoryId();
                if (!parentIds.contains(parentId)) {
                    parentIds.add(parentId);
                    pcbParentFactoryInfoMap.add(pcbParentFactoryInfo);
                }
            }

            for (int i = 0; i < pcbParentFactoryInfoMap.size(); i++) {
                Integer parentId = pcbParentFactoryInfoMap.get(i).getPcbParentFactoryId();
                List<PcbSonFactoryInfo> sonFactoryInfoList = new ArrayList<>();
                for (int j = 0; j < sonFactoryInfoMap.size(); j++) {
                    if (sonFactoryInfoMap.get(j).getParentId() == parentId) {
                        if (flag != null) {
                            PcbOpenCapacityAuthentication search = new PcbOpenCapacityAuthentication();
                            search.setFactoryId(sonFactoryInfoMap.get(j).getPcbSonFactoryId());
                            List<PcbOpenCapacityAuthentication> pcbOpenCapacityAuthenticationList = pcbOpenCapacityAuthenticationDao.getAllByLimitByDesc(search);
                            if (pcbOpenCapacityAuthenticationList.size() > 0) {
                                sonFactoryInfoMap.get(j).setAuthenticationStatus(pcbOpenCapacityAuthenticationList.get(0).getApproveStatus());
                            }
                        }
                        sonFactoryInfoList.add(sonFactoryInfoMap.get(j));
                    }
                }
                pcbParentFactoryInfoMap.get(i).setSonFactoryInfos(sonFactoryInfoList);
            }
            result = pcbParentFactoryInfoMap;
        }

        return result;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insert(PcbParentFactoryInfo param) {
        try {
            String userId = UserHeaderHolder.getUserId();
            PcbParentFactoryInfo search = new PcbParentFactoryInfo();
            search.setCompanyName(param.getCompanyName());
            search.setCompanyCode(param.getCompanyCode());
            List<PcbParentFactoryInfo> items = pcbParentFactoryInfoDao.getAllByLimit(search);
            if (items.stream().count() > 0) {
                return ResultUtil.error(500, "company已存在", "company exist", null);
            } else {
                int count = pcbParentFactoryInfoDao.insert(param);
                if (count > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB板厂管理", 1, 1, new Date(), null, JSONObject.toJSONString(param)));
                    return ResultUtil.success(param);
                } else {
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result delete(Integer id) {
        try {
            String userId = UserHeaderHolder.getUserId();
            String oldData = JSONObject.toJSONString(pcbParentFactoryInfoDao.getById(id));
            int count = pcbParentFactoryInfoDao.delete(id);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB板厂管理", 2, 1, new Date(), oldData, null));
                return ResultUtil.success(null);
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result update(PcbParentFactoryInfo param) {
        try {
            String userId = UserHeaderHolder.getUserId();
            String oldData = JSONObject.toJSONString(pcbParentFactoryInfoDao.getById(param.getPcbParentFactoryId()));
            int count = pcbParentFactoryInfoDao.update(param);
            PcbSonFactoryInfo search = new PcbSonFactoryInfo();
            search.setParentId(param.getPcbParentFactoryId());
            List<PcbSonFactoryInfo> allByLimit = pcbSonFactoryInfoDao.getAllByLimit(search);
            if (allByLimit.size() > 0) {
                for (int i = 0; i < allByLimit.size(); i++) {
                    allByLimit.get(i).setCompanyName(param.getCompanyName());
                    allByLimit.get(i).setCompanyNameEn(param.getCompanyNameEn());
                    allByLimit.get(i).setCompanyWebsite(param.getCompanyWebsite());
                    allByLimit.get(i).setCompanyCode(param.getCompanyCode());
                    allByLimit.get(i).setCompanySort(param.getSort());
                    pcbSonFactoryInfoDao.update(allByLimit.get(i));
                }
            }
            if (count > 0) {
                String newData = JSONObject.toJSONString(pcbParentFactoryInfoDao.getById(param.getPcbParentFactoryId()));
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB板厂管理", 3, 1, new Date(), oldData, newData));
                return ResultUtil.success(null);
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public PcbParentFactoryInfo getById(Integer id) {
        return pcbParentFactoryInfoDao.getById(id);
    }

    @Override
    public boolean checkHasSonFactory(Integer factoryId) {
        PcbSonFactoryInfo search = new PcbSonFactoryInfo();
        search.setParentId(factoryId);
        List<PcbSonFactoryInfo> oldDataList = pcbSonFactoryInfoDao.getAllByLimit(search);
        if (oldDataList != null && oldDataList.size() > 0) {
            return false;
        }
        return true;
    }

    @Value("${personal.config.file.file-save-url}")
    private String rootPath;
    @Override
    public Result output() {
        try{
            List<PcbParentFactoryInfo> pcbParentFactoryInfoList = getAll();
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet("Sheet1");
            Row rowTR = sheet.createRow(0);
            Cell cellTR0 = rowTR.createCell(0);
            cellTR0.setCellValue("下载时间：");
            cellTR0.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell cellTR1 = rowTR.createCell(1);
            cellTR1.setCellValue(format2.format(new Date()));
            Cell cellTR2 = rowTR.createCell(2);
            cellTR2.setCellValue("下载人员：");
            cellTR2.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell cellTR3 = rowTR.createCell(3);
            cellTR3.setCellValue(UserHeaderHolder.getDomainAccount());

            Row rowTR1 = sheet.createRow(1);
            Cell rowTR10 = rowTR1.createCell(0);
            rowTR10.setCellValue("序号");
            rowTR10.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell rowTR11 = rowTR1.createCell(1);
            rowTR11.setCellValue("厂家编码");
            rowTR11.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell rowTR12 = rowTR1.createCell(2);
            rowTR12.setCellValue("公司中文全称");
            rowTR12.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell rowTR13 = rowTR1.createCell(3);
            rowTR13.setCellValue("公司中文简称");
            rowTR13.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell rowTR14 = rowTR1.createCell(4);
            rowTR14.setCellValue("公司英文名称");
            rowTR14.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell rowTR15 = rowTR1.createCell(5);
            rowTR15.setCellValue("公司官网");
            rowTR15.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell rowTR16 = rowTR1.createCell(6);
            rowTR16.setCellValue("排序");
            rowTR16.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell rowTR17 = rowTR1.createCell(7);
            rowTR17.setCellValue("状态");
            rowTR17.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            Cell rowTR18 = rowTR1.createCell(8);
            rowTR18.setCellValue("创建时间");
            rowTR18.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, true, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));

            int rowIndex = 2;
            for(int i=0;i < pcbParentFactoryInfoList.size();i++){
                rowIndex = 2+i;
                Row rowTRi = sheet.createRow(rowIndex);
                Cell rowTRi0 = rowTRi.createCell(0);
                rowTRi0.setCellValue(i+1);
                rowTRi0.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
                Cell rowTRi1 = rowTRi.createCell(1);
                rowTRi1.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyCode());
                rowTRi1.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
                Cell rowTRi2 = rowTRi.createCell(2);
                rowTRi2.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyNameFull());
                rowTRi2.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
                Cell rowTRi3 = rowTRi.createCell(3);
                rowTRi3.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyName());
                rowTRi3.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
                Cell rowTRi4 = rowTRi.createCell(4);
                rowTRi4.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyNameEn());
                rowTRi4.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
                Cell rowTRi5 = rowTRi.createCell(5);
                rowTRi5.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyWebsite());
                rowTRi5.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
                Cell rowTRi6 = rowTRi.createCell(6);
                rowTRi6.setCellValue(pcbParentFactoryInfoList.get(i).getSort());
                rowTRi6.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
                Cell rowTRi7 = rowTRi.createCell(7);
                rowTRi7.setCellValue(pcbParentFactoryInfoList.get(i).getStatus());
                rowTRi7.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
                Cell rowTRi8 = rowTRi.createCell(8);
                rowTRi8.setCellValue(pcbParentFactoryInfoList.get(i).getCreateTime().toString());
                rowTRi8.setCellStyle(ExcelStyleUtil.setBorderAndFont(workbook, BorderStyle.THIN, false, IndexedColors.BLACK.getIndex(),IndexedColors.WHITE.getIndex()));
            }

            sheet.setColumnWidth(0, 5 * 256);
            sheet.setColumnWidth(1, 10 * 256);
            sheet.setColumnWidth(2, 20 * 256);
            sheet.setColumnWidth(3, 15 * 256);
            sheet.setColumnWidth(4, 12 * 256);
            sheet.setColumnWidth(5, 12 * 256);
            sheet.setColumnWidth(6, 12 * 256);
            sheet.setColumnWidth(7, 12 * 256);
            sheet.setColumnWidth(8, 12 * 256);

            // 导出Excel文件
            String filename = "PCB板厂" + String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            String filePath = rootPath + "pcb\\" + format + "\\" + filename + ".xlsx";
            File folder = new File(rootPath + "pcb\\" + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(filePath);
        }
        catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
